<template>
  <div>
    <!--:model="form"   v-model  不行双向绑定  ref="form"  后面按钮时间 判断 -->
    <el-form ref="form" :model="form" :rules="rules" label-width="80px;" class="login-box">
      <h3 class="login-title">welcome to login page</h3>
      <el-form-item label="用户名" prop="username">
        <el-input type="text" placeholder="请输入用户名" v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" placeholder="请输入密码" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="margin-left:30px;" @click="onSubmit('form')">登录</el-button>
        <router-link to="/user/register">
          <el-button type="success" style="margin-left:120px;">注冊</el-button>
        </router-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      form: {
        username: "",
        password: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 20, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 20, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    onSubmit: function(formName) {
      this.$refs[formName].validate(valid => {
        //表单数据验证  注意 要双向绑定

        if (valid) {
          let params = {
            username: this.form.username,
            password: this.form.password
          };
            this.$axiosGet("/api-user/login",params).then(result => {
               let data = result.data;
                 if (data.status) {
                //模拟登录成功  存状态
                localStorage.setItem("isLogin", this.form.username);
                sessionStorage.setItem("isLogin", this.form.username);
                localStorage.setItem("token", data.data.token);
                let user=data.data.user;
                console.log(user)
                this.$store.dispatch("asyncUpdateUser", {
                  username: this.form.username,
                  id:user.id,
                });
                this.$router.push({
                  name: "Main",
                  params: { username: this.form.username,id:user.id }
                }); //通过路由跳转页面
              } else {
                this.form.password = null;
                this.message.warningMsg(data.message);
              }
            })
           
        }
      });
    }
  }
};
</script>

<style scoped>
.login-box {
  width: 350px;
  margin: 180px auto;
  border: 1px solid #dcdfe6;
  padding: 35px;
  border-radius: 5px;
  box-shadow: 0 0 25px #dcdfe6;
}
.login-title {
  text-align: center;
}
</style>
